package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("authorization");
        //判断token是否为空 为空则返回401
        if(StringUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //如果不为空则解析token
        Claims claims ;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //如果解析失败则返回401
    if(ObjectUtils.isEmpty(claims)){
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
        //如果解析成功获取数据
        Long userId = Long.valueOf(String.valueOf(claims.get("userId")));
       // Long userId = MapUtils.getLong(claims,"userId");
        //如果数据为空  返回401
        if(ObjectUtils.isEmpty(userId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //将userid存储到threadlocal当中
        UserThreadLocal.set(userId);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //将userid从threadlocal当中移除
        UserThreadLocal.remove();
    }
}
